import CryptoJS from 'crypto-js'

/**

* @param {*需要加密的字符串 注：对象转化为json字符串再加密} word

* @param {*aes加密需要的key值，这个key值后端同学会告诉你} keyStr

*/

const SECRET_KEY = 'nHwsk9MvRJhc5wRN'
const SECRET_IV = 'Xadiapdfaxi0s91D'
export function getKey () {
  // 真正的key
  return CryptoJS.enc.Utf8.parse(SECRET_KEY)
}

export function getIv () {
  // 真正的iv
  return CryptoJS.enc.Utf8.parse(SECRET_IV)
}
// AES加密
export function encrypt (data) {
  if (typeof data === 'object') {
    try {
      // eslint-disable-next-line no-param-reassign
      data = JSON.stringify(data)
    } catch (error) {
      console.log('encrypt error:', error)
    }
  }
  const dataHex = CryptoJS.enc.Utf8.parse(data)
  const encrypted = CryptoJS.AES.encrypt(dataHex, getKey(), {
    iv: getIv(),
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  })
  return CryptoJS.enc.Base64.stringify(encrypted.ciphertext)
}

export function decrypt (data) {
  const Base64 = CryptoJS.enc.Base64.parse(data)
  const str = CryptoJS.enc.Base64.stringify(Base64)
  const decrypt = CryptoJS.AES.decrypt(str, getKey(), {
    iv: getIv(),
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  })
  const decryptedStr = decrypt.toString(CryptoJS.enc.Utf8)
  return decryptedStr.toString()
}
